var express = require('express');
var router = express.Router();
var db = require("../db");
var moment = require("moment");

function getPages(page, pageCount) {
  var pages = [page];
  var left = page - 1;
  var right = page + 1;
  while (pages.length < 11 && (left > 0 || right <= pageCount)) {
    if (left > 0) {
      pages.unshift(left--);
    }
    if (right <= pageCount) {
      pages.push(right++);
    }
  }

  return pages;
}

/* GET home page. */
router.get('/list/:page', function (req, res) {

  // 查询条件
  var filter = {}

  // 查询条件在url的查询字符串中
  var name = req.query.name;
  var gender = req.query.gender;
  var mobile = req.query.mobile;
  var email = req.query.email;
  var minAge = req.query.minAge;
  var maxAge = req.query.maxAge;

  // 如果查询字段存在，则使用正则查询
  if (!!name) {
    // $regex: `.*?${name}.*?` 正则匹配查询
    filter.name = { $regex: `.*?${name}.*?` };
  }
  if (!!gender) {
    filter.gender = { $regex: `.*?${gender}.*?` };
  }
  if (!!mobile) {
    filter.mobile = { $regex: `.*?${mobile}.*?` };
  }
  if (!!email) {
    filter.email = { $regex: `.*?${email}.*?` };
  }
  if (!!minAge || !!maxAge) {
    filter.age = {
      $lte: maxAge,
      $gte: minAge
    }
  }

  var pageSize = 3;

  var page = req.params.page;

  page = parseInt(page);

  page = page || 1;

  // 查询符合该条件的数据量
  db.Student.find(filter).count(function (err, count) {
    var pageCount = Math.ceil(count / pageSize);
    
    if (page >= pageCount) {
      page = pageCount;
    }

    if (page <= 1) {
      page = 1;
    }
    // 根据查询到的符合该条件的数据进行分页显示
    db.Student.find(filter)
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .exec(function (err, students) {
        if (!err) {
          res.render("index", {
            page: page,//当前页
            pages: getPages(page, pageCount),//获取页码数组
            pageCount: pageCount,// 总页数
            // 处理返回的结果
            students: students.map(function (student) {
              var k = student.toObject();
              k.dateForShow = moment(student.birthday).format("YYYY-MM-DD");
              k.id = student._id.toString();
              return k;
            }),
            query: req.query// 查询字段
          })
        } else {
          console.log(err);
        }
      })
  })
});

module.exports = router;
